package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {
    @Autowired
    private CategoryBrandService categoryBrandService;
    @Override
    public PageDTO<BrandDTO> queryBrandByPage(Integer page, Integer rows, String key) {
//       分页信息的健壮性处理
        page = Math.min(page, 100);
        rows = Math.max(rows, 5);
//        分页
        Page<Brand> info = new Page<>(page, rows);
//        判断key是否存在
        boolean isKeyExists = StringUtils.isNoneBlank(key);
//        如果key存在，添加like和eq的查询条件，否在不添加
        query().like(isKeyExists, "name", key)
                .or()
                .eq(isKeyExists, "letter", key)
                .page(info);
//        分装结果
        List<Brand> list = info.getRecords();
        return new PageDTO<>(info.getTotal(), info.getPages(), BrandDTO.convertEntityList(list));
    }

//    根据分类id查询品牌
    @Override
    public List<BrandDTO> queryBrandByCategory(Long id) {
        List<Brand> brandList = getBaseMapper().queryBrandByCategory(id);

        return BrandDTO.convertEntityList(brandList);
    }

    //    新增品牌
    @Transactional
    @Override
    public void saveBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
//        保存品牌信息
         save(brand);
//封装中间表对象的集合
        List<CategoryBrand> list = brandDTO.getCategoryIds().stream()
                .map(id -> CategoryBrand.of(id, brand.getId()))
                .collect(Collectors.toList());
//        批量写入中间表数据
        categoryBrandService.saveBatch(list);
    }
//    更新品牌


    @Override
    public void updateBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        boolean result = updateById(brand);
        if(!result){
//            更新失败后抛出异常
            throw new LyException(500, "更新品牌失败");
        }


//       根据品牌id删除中间表数据
        categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", brandDTO.getId()));
        if(!result){
            throw new LyException(500, "更新品牌失败，删除中间表错误数据");
        }
//重新插入中间表数据
        List<CategoryBrand> list = brandDTO.getCategoryIds().stream()
                .map(id -> CategoryBrand.of(id, brandDTO.getId()))
                .collect(Collectors.toList());
//        pil写入中间表数据
        categoryBrandService.saveBatch(list);


    }
}
